package top.lwaiting.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import top.lwaiting.io.Resources;
import top.lwaiting.pojo.Configuration;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author YANG
 * @version V1.0
 * @date 2024/1/15 15:56
 * @see XMLConfigBuilder
 **/
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 将配置文件进行解析，封装 Configuration
     * 使用 Dom4j 对配置文件进行解析
     * @param inputStream {@link InputStream}
     * @return {@link Configuration}
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(inputStream);
        // 获取文件根对象，<configuration>
        Element rootElement = document.getRootElement();
        // 获取所有的 property 节点对象(dataSource 等配置信息)，封装到Configuration start
        List<Element> dataSourcePropertiesList = rootElement.selectNodes("//property");

        // 将 DataSource 的配置信息封装到 Properties 对象
        Properties properties = new Properties();
        for (Element element : dataSourcePropertiesList) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }

        // 数据库连接池对象封装
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        // 封装到 Configuration，end
        configuration.setDataSource(comboPooledDataSource);

        // Mapper.xml 解析 拿到 Mqpper.xml 路径 -> 输入字节流 -> dom4j 进行解析
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            // 拿到 mapperPath 路径
            String mapperPath = element.attributeValue("resource");
            // 加载字节流
            InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
            // dom4j 进行解析
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsStream);
        }

        return configuration;
    }
}
